﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using System.Reflection;
using waveform_test.ext;
using waveform_test.main;
using System.IO;
using System.Threading;
using System.Diagnostics;
using org.dicomcs.data;
using log4net.Repository.Hierarchy;
using log4net.Appender;

namespace waveform_test
{
    public partial class DICOMExploringForm : Form
    {
        private static readonly ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private LogWatcher logWatcher;
        private LogForm logForm;
        private List<LoadDcmFile> loaderList;
        private BackgroundWorker backgroundLoader;

        public DICOMExploringForm()
        {
            InitializeComponent();

            //logForm = new LogForm();
            //logWatcher = new LogWatcher();
            //logWatcher.Updated += new EventHandler(logWatcher_Updated);

            backgroundLoader = new BackgroundWorker();
            backgroundLoader.WorkerReportsProgress = true;
            backgroundLoader.DoWork += new DoWorkEventHandler(backgroundLoader_DoWork);
            backgroundLoader.ProgressChanged += new ProgressChangedEventHandler(backgroundLoader_ProgressChanged);
            backgroundLoader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundLoader_RunWorkerCompleted);

            log.Info("Starting MainEntryForm ...");

            pathTxt.Text = @"C:\Desarrollo .net\Imagenologia\Librerias\DICOM#\dicomSrc-0_2_3\dicom-cs\waveform-test\test-data\1.2.826.0.1.3680043.8.886.20130603100503.368.11.5\1.2.826.0.1.3680043.8.886.20130603100503.368.11.6";
        }

        void backgroundLoader_DoWork(object sender, DoWorkEventArgs e)
        {
            FileInfo[] files = (FileInfo[])e.Argument;
            int stepCount = files.Length;
            int step = 0;

            foreach (FileInfo file in files)
            {
                LoadDcmFile loader = new LoadDcmFile();
                loader.Load(file);

                step++;

                backgroundLoader.ReportProgress(
                        Convert.ToInt32(Math.Ceiling(Convert.ToDouble(step) / Convert.ToDouble(stepCount) * 100)), 
                        new LoaderProgress(string.Format("Cargado {0} de {1}", step, stepCount), loader)
                    );
            }
        }

        void backgroundLoader_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            LoaderProgress status = (LoaderProgress)e.UserState;
            loaderList.Add(status.Loader);
            
            loadDcmProgress.Value = e.ProgressPercentage;
            loadDcmProgress.Refresh();

            estadoStripStatusLabel.Text = status.Message;

            ListViewItem item = new ListViewItem();
            item.Text = status.Loader.File.Name;
            item.Tag = status.Loader;

            loadDcmListView.Items.Add(item);
            loadDcmListView.Refresh();
        }

        void backgroundLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            loadDcmBtn.Enabled = true;
        }

        private void loadDcmBtn_Click(object sender, EventArgs e)
        {
            loadDcmBtn.Enabled = false;
            loaderList = new List<LoadDcmFile>();
            loadDcmListView.Items.Clear();
            loadDcmProgress.Value = 0;

            string[] pathArray = pathTxt.Text.Split(new char[] { ';' });
            foreach (string path in pathArray)
            {
                
                if (path.Trim() != string.Empty)
                {
                    FileInfo[] files;
                    if (System.IO.File.Exists(path))
                    {
                        files = new FileInfo[] { new FileInfo(path) };
                    }
                    else
                    {
                        DirectoryInfo dir = new DirectoryInfo(path);
                        files = dir.GetFiles();
                    }

                    backgroundLoader.RunWorkerAsync(files);
                }
            }
        }

        public void logWatcher_Updated(object sender, EventArgs e)
        {
            if (InvokeRequired)
            {
                // this.BeginInvoke(new Action<string>(UpdateLogTextbox), new object[] { value });
                this.BeginInvoke(new MethodInvoker(delegate { logWatcher_Updated(sender, e); }));
                return;
            }
            logForm.UpdateLogTextbox(logWatcher.LogContent);
        }

        private void logToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var rootAppender = ((Hierarchy)LogManager.GetRepository()).Root.Appenders.OfType<FileAppender>().FirstOrDefault();
            string filename = rootAppender != null ? rootAppender.File : string.Empty;
            Process.Start(filename);
            //logForm.Show();
        }

        private void loadDcmListView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem clickedItem = ((ListView)sender).FocusedItem;
            LoadDcmFile loader = (LoadDcmFile)clickedItem.Tag;

            var explorer = new DICOMPropertiesExplorerForm(loader.Ds);
            explorer.ShowDialog();

        }
    }
}
